import { Component, inject, OnInit } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';

import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCheckboxModule } from 'ng-zorro-antd/checkbox';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzInputModule } from 'ng-zorro-antd/input';
import { LoginService } from './login.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  imports: [ 
    ReactiveFormsModule, 
    NzButtonModule, 
    NzCheckboxModule, 
    NzFormModule, 
    NzInputModule,
  ],
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  private fb = inject(NonNullableFormBuilder);
  private msg = inject(NzMessageService)
  private loginSvc = inject(LoginService)
  private router = inject(Router)
  codeUrl = "";
  validateForm = this.fb.group({
    username: this.fb.control('', [Validators.required]),
    password: this.fb.control('', [Validators.required]),
    rememberMe: this.fb.control(true),
    code: "",
    uuid: ""
  });

  ngOnInit(): void {
    this.loadCode();
  }

  loadCode() {
    this.loginSvc.getCodeImg().subscribe(res => {
      this.codeUrl = "data:image/gif;base64," + res.data.img;
      const currentValue = this.validateForm.value;
      // this.validateForm.setValue({
      //   username: currentValue.username || '',
      //   password: currentValue.password || '',
      //   rememberMe: currentValue.rememberMe || false,
      //   code: currentValue.code || '',
      //   uuid: res.data.uuid
      // });
      this.validateForm.patchValue({
        uuid: res.data.uuid
      });
    })
  }

  submitForm(): void {
    if (this.validateForm.valid) {
      // 确保所有必需字段都有值
      const formValue = this.validateForm.value;
      const loginData = {
        username: formValue.username || '',
        password: formValue.password || '',
        rememberMe: formValue.rememberMe || false,
        code: formValue.code || '',
        uuid: formValue.uuid || ''
      };
      
      this.loginSvc.login(loginData).subscribe(res => {
        console.log(res);
        if(res.code === 200) {
          localStorage.setItem('token', res.data.token);
          this.msg.success("登录成功");
          this.router.navigateByUrl('/')
        } else {
          this.msg.error(res.msg);
          this.loadCode();
        }
      }, err => {
        this.msg.error(err.msg);
        this.loadCode();
      });
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
}
